<?php

class Model_User extends Bcms_Db_Table
{
    const SUPERUSER_ROLE = 'superadmin';
    /**
     * table name
     *
     * @var string
     */
    protected $_name = 'users';
    
    /**
     * primary key
     * @var int
     */
    protected $_primary = 'id';
    
    /*
     * Get All users
     */
    public function getAllUsers($isPost)
    {
    	if($isPost){
    		extract($_POST);
    		
    		$where 	= 	$this->_db->quoteInto(' username like ?'	, 	"%{$username}%")
    					.$this->_db->quoteInto(' AND email like ?'	, 	"%{$email}%")
			    		.$this->_db->quoteInto(' AND ip like ?'		, 	"%{$ip}%")
			    		.$this->_db->quoteInto(' AND role like ?'		, 	"%{$role}%");
    	}else{
    		$where	=	null;
    	}
    	$order = 'id desc';
    	
    	return $this->fetchAll($where,$order);
    }
    
    /**
     * create user
     * @return a new userid
     */
    public function createUser($params)
    {
    	foreach($params as $k=>$v){
    		$row[$k] = $v;
    	}
    	$row['register_date'] 	= 	mktime('0','0','0',date('m'),date('d'),date('Y'));
    	$row['ip']				= 	$this->getOnlineIp(); 
    	
		$this->_db->insert($this->_name,$row);
		return $this->_db->lastInsertId();
		    	
    }
    
    /*
     * Ajax UserName
     */
    public function getUserByName($username)
    {
    	$where = $this->_db->quoteInto('username = ?', $username);
    	$order = 'id';

		$row = $this->fetchRow($where, $order);
		return $row;
    }
    
    /**
     * Ip
     * @return online ip
     */
    public function getOnlineIp()
    {
	    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
		$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
		unset($onlineipmatches);
		
		return $onlineip;
    }
    
    

    public function updatePassword($id, $p_modified,$password, $confirmationRequire = true, $confirmation = null,$email,$role)
    {
        $person = $this->find($id)->current();
        if ($person) {
            if ($confirmationRequire == true && $p_modified) {
                if ($confirmation != $password) {
                    return false;
                }
            }
            if($p_modified) $person->password = md5($password);
            
			$person->email = $email;
			$person->role = $role;
            $result = $person->save();
            return $result;
        } else {
            return false;
        }
    }

    public function updateAclResources($userId, $resourceArray)
    {
        $data['acl_resources'] = serialize($resourceArray);
        $where[] = $this->_db->quoteInto('id = ?', $userId);
        return $this->update($data, $where);
    }

    public function getAclResources($userRowset)
    {
    	//select * from users inner join user_role on users.role = user_role.name
    	$select = $this->_db->select()->from('user_role','*')  
    									  ->join('users' , 'users.role = user_role.name')
    									  ->where('user_role.name = ?', $userRowset->role)
    									  ->limit(1,0);						  
    	$row = $this->_db->fetchAll($select->__toString());
    	
    	$acl_resources = unserialize($row[0]->u_acl_resources);	
    	
    	return $acl_resources;	
        //return unserialize($userRowset->acl_resources);
    }
    

    /**
     * returns the complete user row for the currently logged in user
     * @return zend_db_row
     */
    public function getCurrentUser()
    {
        $currentUser = Bcms_Auth::getIdentity();
        if ($currentUser) {
            return $this->find($currentUser->id)->current();
        }
    }


    public function getCurrentUsersAclResources()
    {
        $currentUser = $this->getCurrentUser();
        if ($currentUser) {
            return $this->getAclResources($currentUser);
        }
    }

    public function getCurrentUsersModules()
    {
        return $this->getUsersModules($this->getCurrentUser());
    }

    public function getUsersModules($userRowset)
    {
        $modules = null;
        $user = $this->getCurrentUser();
        if ($user->role == Model_User::SUPERUSER_ROLE) {
            //the superadmin has access to all of the modules
            $front = Zend_Controller_Front::getInstance();
            $ctlPaths = $front->getControllerDirectory();
            foreach ($ctlPaths as $module => $path) {
                if (substr($module, 0, 4) == 'mod_') {
                    $modules[] = str_replace('mod_', '', $module);
                }
            }
        } else {
            $resources = $this->getAclResources($userRowset);
            if (is_array($resources)) {
                foreach ($resources as $k => $v) {
                    if (1 == $v ) {
                        $parts = explode('_', $k);
                        if ('mod' == $parts[0]) {
                            $key = $parts[1];
                            $modules[$key] = $key;
                        }
                    }
                }
            }
        }
        if (is_array($modules)) {
            return $modules;
        }
    }

    
    /**
     * this function queries a users permissions
     *
     * the resource should be in the module_controller_action format
     *
     * if strict = true then this requires an exact match
     * example: news_article != news_article_edit
     *
     * if strict = false then it will add wildcards
     * example: news_article == news_article_edit
     *
     * if user is not set then the query will be run on the current user
     *
     * @param string $resource
     * @param boolean $strict
     * @param integer $user
     * @return boolean
     */
    public function queryPermissions($resource, $strict = false, $userId = null)
    {
        if ($userId !== null) {
            $user = $this->find($userId)->current();
            if (!$user) {
                return false;
            }
            $resources = $this->getAclResources($user);
        } else {
            $resources = $this->getCurrentUsersAclResources();
        }

        if (is_array($resources)) {
            if ($strict) {
                if (array_key_exists($resource, $resources) && 1 == $resources[$resource]) {
                    return true;
                }
            } else {
                $len = strlen($resource);
                foreach ($resources as $r => $v) {
                    if (1 == $v && $resource == substr($r, 0, $len)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public function getUserByUsername($userName)
    {
        $where[] = $this->_db->quoteInto('email = ?', $userName);
        return $this->fetchRow($where);
    }

    /**
     * @since 0.8.7
     *
     * returns a hash of the current users
     * their id is the key and their first_name . ' ' . last_name is the value
     *
     */
    public function getUserNamesArray()
    {
        $users = $this->fetchAll();
        foreach ($users as $user) {
            $usersArray[$user->id] = $user->first_name . ' ' . $user->last_name;
        }
        return $usersArray;
    }

    public function copyPermissions($from, $to)
    {
        $fromUser = $this->find($from)->current();
        $toUser = $this->find($to)->current();
        $toUser->acl_resources = $fromUser->acl_resources;
        return $toUser->save();
    }
    
    /**
     * Make a login's log
     */
    public  function log($p_username,$operate )
    {
    	 $now = date('Y-m-d H:i:s');
		 $ip = $this->getOnlineIp();
		 
		 $arr = array(
		 	'username' 	=> $p_username,	
		 	'ip' 		=> $ip,
		 	'oper' 		=> $operate,
		 	'oper_date' => $now,
		 	);
    	 $this->_db->insert('user_log',$arr);
    	
    }

}
